<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @change="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogFormVisible =true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 点击添加弹框显示 -->
      <el-dialog title="添加数据" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="用户名称" label-width="120px">
            <el-input v-model="form.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" label-width="120px">
            <el-input v-model="form.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" label-width="120px">
            <el-input v-model="form.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话" label-width="120px">
            <el-input v-model="form.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="add">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 点击修改弹框显示 -->
      <el-dialog title="修改数据" :visible.sync="dialogFormVisiblexg">
        <el-form :model="updata">
          <el-form-item label="用户名称" label-width="120px">
            <el-input v-model="updata.username" autocomplete="off" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" label-width="120px">
            <el-input v-model="updata.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话" label-width="120px">
            <el-input v-model="updata.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisiblexg = false">取 消</el-button>
          <el-button type="primary" @click="addxg">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配角色弹框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="dialogVisibleRole"
        width="30%"
        @close="setRoleDialogclosed"
      >
        <div>当前的用户：{{uesrinfo.username}}</div>
        <div>当前的角色：{{uesrinfo.role_name}}</div>
        <div>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleRole = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 用户列表(表格)区域 -->
    <el-table :data="userList" stripe style="width: 100%">
      <el-table-column type="index" label="#" width="180"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column label="电话" prop="mobile"></el-table-column>
      <el-table-column label="角色" prop="role_name"></el-table-column>
      <el-table-column label="状态" prop="mg_state">
        <template v-slot="scope">
          <div>
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <!-- 修改 -->
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="xg(scope.row)"></el-button>
          <!-- 删除 -->
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="del(scope.row.id)"></el-button>
          <!-- 分配角色 -->
          <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页导航区域 
@size-change(pagesize改变时触发) 
@current-change(页码发生改变时触发)
:current-page(设置当前页码)
:page-size(设置每页的数据条数)
    :total(设置总页数)-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // /获取查询用户信息的参数
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5
      },
      //保存请求回来的用户列表数据
      userList: [],
      total: 0,
      // 添加弹框
      dialogFormVisible: false,
      // 修改弹框
      dialogFormVisiblexg: false,
      // 添加用户
      form: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //编辑 表单回填
      updata: {},
      // 分配角色
      dialogVisibleRole: false,
      // 需要被分配的用户信息
      uesrinfo: {},
      // 所有角色的数据列表
      roleList: [],
      // 已选中的角色id
      selectedRoleId: ""
    };
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    // 用户列表
    async getUserList() {
      let { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });
      console.log(res);
      //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败");
      //如果返回状态正常，将请求的数据保存在data中
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val;
      // 刷新页面
      this.getUserList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val;
      // 刷新页面
      this.getUserList();
    },
    // 点击确认添加数据
    add() {
      this.$http.post("users", this.form).then(res => {
        // console.log(res);
        if (res.data.meta.status !== 201)
          return this.$message.error("添加用户失败");
        //添加成功的提示
        this.$message.success("添加用户成功");
      });
      // 刷新页面
      this.getUserList();
      // 关闭弹框
      this.dialogFormVisible = false;
    },
    // 修改用户状态
    async userStateChanged(row) {
      // console.log(row);
      let { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      );
      // console.log(res);
      //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state;
        return this.$message.error("修改状态失败");
      }
      this.$message.success("更新状态成功");
    },
    //编辑 表单回填
    xg(row) {
      // console.log(row);
      this.updata = row;
      this.dialogFormVisiblexg = true;
    },
    // 点击确定修改内容
    async addxg() {
      let { data: res } = await this.$http.put(
        // "users/" + this.updata.id,
        // this.updata
        `users/${this.updata.id}`,
        this.updata
      );
      console.log(res);
      if (res.meta.status != 200) {
        this.$message.error("修改用户失败");
      }
      //修改成功的提示
      this.$message.success("修改用户成功");
      //关闭对话框
      this.dialogFormVisiblexg = false;
      //重新请求最新的数据
      this.getUserList();
    },
    // 点击删除
    async del(id) {
      let { data: res } = await this.$http.delete(`users/${id}`);
      // console.log(res);
      //如果返回状态为异常状态则报错并返回
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      // 刷新页面
      this.getUserList();
    },
    // 点击分配角色
    async setRole(rows) {
      this.uesrinfo = rows;
      // 请求数据
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      this.roleList = res.data;
      this.dialogVisibleRole = true;
    },
    // 点击确定分配角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error("请选择要分配的角色！");
      }
      const { data: res } = await this.$http.put(
        `users/${this.uesrinfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("更新角色失败！");
      }
      this.$message.success("更新角色成功！");
      this.getUserList();
      this.dialogVisibleRole = false;
    },
    //监听分配对话框的关闭事件
    setRoleDialogclosed() {
      this.selectedRoleId = "";
      this.uesrinfo = {};
    }
  }
};
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 20px;
}
</style>